<template>
  <div class="container">
    <search-nav :statusBarHeight="statusBarHeight" color="#7427FF" searchType="seller-self"></search-nav>
    <div class="tabs-wrap" :style="{'top': statusBarHeight + 'px'}">
      <van-tabs :active="activeIndex" @change="tabClick" :border="false">
        <van-tab :title="item" v-for="(item, index) in orderStatusList" :key="index"></van-tab>
      </van-tabs>
    </div>
    <div :style="{'padding-top': 36 + 'px;'}">
      <div v-for="(item, index) in orders" :key="index">
        <div class="order-div">
          <div class="pad-15">
            <div class="flex flex-between mar-b-16 line-h-1">
              <div class="font-14 font-w">订单号：{{item.orderNo}}</div>
              <div class="font-14 font-w" style="color: #F8303D;">{{orderStatusMap[item.orderStatus]}}</div>
            </div>
            <div
              class="mar-b-20"
              v-for="(goods, goodsIndex) in item.orderGoodsList"
              :key="goodsIndex"
              @click="queryOrderInfo(item)">
              <div class="flex mar-b-10">
                <div class="mar-r-10"><img :src="goods.goodsImageUrl" class="img-item" /></div>
                <div class="flex-item">
                  <div class="item-bar-l">
                    <div>
                      <div class="goods-title mar-t--3">{{ goods.goodsTitle }}</div>
                      <div class="flex flex-between font-color-9 mar-t-10" v-if="goods.skuDetail">
                        <div class="goods-prop font-11">{{ goods.skuDetail }}</div>
                        <div class="font-15 align-r"> ×{{ goods.goodsNum }}</div>
                      </div>
                    </div>
                    <div class="flex v-align-c">
                      <div class="font-12 flex-item" style="color: #F82A37;" v-if="goods.goodsPrice === '0.00'">免费寄样</div>
                      <div class="font-12 font-w flex-item v-align-c" v-else>
                        <span class="pad-t-4 pad-r-1">¥</span>
                        <span class="font-16">{{goods.goodsPrice}}</span>
                        <span class="font-12 font-normal font-color-9 pad-l-4">(观众价:¥{{goods.originalPrice}})</span>
                      </div>
                      <div class="font-15 align-r font-color-9" v-if="!goods.skuDetail"> ×{{ goods.goodsNum }}</div>
                    </div>
                  </div>
                  <!--  退款关闭: -3、4、3（数量全退完）
                      退款：-2、-1、3(数量未退完)、''
                      退款中：0、1、2 -->
                  <div v-if="item.goodsAmount * 1 > 0" class="flex">
                    <div class="flex-item"></div>
                    <template v-if="urlFrom !== 'myDistribution'">
                      <template v-if="item.orderStatus !== -2 && item.orderStatus !== -1 && item.orderStatus !== 0 && item.orderStatus !== 4">
                        <div @click.stop="linkToDetail(goods)"
                          v-if="!goods.afterSaleGoodsNum && (goods.afterSaleStatus===0 || goods.afterSaleStatus===1 || goods.afterSaleStatus===2 )">
                          <div class="action-btn font-13 mar-t-10">退款中</div>
                        </div>
                        <div class="action-btn font-13 mar-t-10" @click.stop="linkToDetail(goods)"
                          v-else-if="goods.afterSaleStatus===-3 || goods.afterSaleStatus===4 || (goods.afterSaleStatus===3 && (goods.afterSaleGoodsNum <= goods.goodsNum))">退款成功</div>
                      </template>
                    </template>
                  </div>
                </div>
              </div>
              <div v-if="getRoleType !== 2" class="flex v-align-b font-12 ratio-bar pad-b-5">
                <div class="flex-item pad-l-25">
                  <div class="flex v-align-c pad-t-4">
                    <div class="font-color-9 font-11 pad-r-8">主播佣金</div>
                    <div class="font-12">{{ goods.anchorRatio ? goods.anchorRatio : '0.00' }}%</div>
                  </div>
                </div>
              </div>
              <div v-else class="flex v-align-b font-12 ratio-bar pad-t-3 pad-b-5">
                <div class="flex-item pad-l-25">
                  <div>{{ goods.sampleTotalPartnerRatio ? goods.sampleTotalPartnerRatio : '0.00' }}%</div>
                  <div class="font-color-9 font-11 mar-t--4">应获佣金</div>
                </div>
                <div class="flex-item">
                  <div>{{ goods.samplePartnerRatio ? goods.samplePartnerRatio : '0.00' }}%</div>
                  <div class="font-color-9 font-11 mar-t--4">实获佣金</div>
                </div>
                <div class="mar-r-25">
                  <div>{{ goods.sampleAnchorRatio ? goods.sampleAnchorRatio : '0.00' }}%</div>
                  <div class="font-color-9 font-11 mar-t--4">主播佣金</div>
                </div>
              </div>
            </div>
            <div class="font-w font-14 mar-t--7 text-align-r">
              <span>合计：{{item.orderPrice}}</span>
              <span class="mar-l-10">共{{item.goodsCount}}件</span>
            </div>
          </div>
          <div class="opration-row pad-r-15">
            <template v-if="item.orderStatus !== 0 && item.orderStatus !== 1">
              <span v-if="item.orderStatus===2 || item.orderStatus===3" class="order-btn mar-r-10" @click="queryExpress(item)">查看物流</span>
              <span v-if="item.orderStatus===2" class="comfirm-btn order-btn mar-r-10" @click="receivingGoods(item)">确认收货</span>
            </template>
            <span v-if="item.orderStatus===0 || (item.orderStatus === 1 && item.cancelFlag === 0)"
                class="order-btn cancel-order mar-r-10" @click="cancelOrder(item)">取消订单</span>
            <!-- <span v-if="item.orderStatus === 0"
                class="comfirm-btn order-btn" @click="queryOrderInfo(item)">去支付</span> -->
          </div>
        </div>
      </div>
      <div class="align-c nodata" v-if="nodata">
        <img v-if="fileSpace" mode="widthFix" class="width-205 height-173" :src="fileSpace + '/images/anchor-nodata.png'" />
        <div class="pad-t-10 font-16 font-color-9">暂无数据</div>
      </div>
    </div>
  </div>
</template>

<script>
import SearchNav from '@/components/SearchNav'
import { pageCustomerOrder, doReceiveGoods, cancelOrder, checkCancelPaidOrder } from '@/api/personal'
import { getDict } from '@/api/common'

export default {
  components: { SearchNav },
  data() {
    return {
      orderStatusList: ['全部', '待发货', '待收货', '已收货'],
      activeIndex: 0,
      orders: [],
      userInfo: {},
      isShowExpressPicker: false,
      statusBarHeight: 0,
      orderStatusMap: {},
      globalStyle: {},
      currentPage: 1,
      nodata: false,
      pullLoad: {
        finished: false,
        loading: false
      }
    }
  },
  onLoad() {
    // 初始化data
    Object.assign(this.$data, this.$options.data())
    this.statusBarHeight = this.$pt.getSystemInfoSync()['statusBarHeight'] + 44
  },
  mounted() {
    let getAppInfo = this.$pt.getStorageSync('appInfo')
    this.globalStyle = getAppInfo.style
    const type = this.getCurrentPage().query.type
    switch (type) {
      case '':
        // 全部
        this.activeIndex = 0
        break
      case 'wDeliver':
        // 待发货
        this.activeIndex = 1
        break
      case 'shipped':
        // 待收货
        this.activeIndex = 2
        break
      case 'received':
        // 已收货
        this.activeIndex = 3
        break
    }
    this.getOrderList()
  },
  onShow() {
    this.getOrderDic()
  },
  onReachBottom() {
    // 触底刷新
    if (!this.pullLoad.finished) {
      this.getOrderList()
    }
  },
  // 下拉刷新
  onPullDownRefresh() {
    this.orders = []
    this.currentPage = 1
    this.pullLoad.finished = false
    this.getOrderList()
    setTimeout(() => {
      this.$pt.stopPullDownRefresh()
    }, 80)
  },
  methods: {
    cancelOrder(item) {
      // 取消订单事件
      // 订单里面都没有发货才可以取消订单，到订单取消页面
      // 否则提示联系卖家处理
      if (item.orderStatus === 0) {
        const that = this
        this.$pt.showModal({
          title: '温馨提示',
          content: '确认取消订单?',
          success: res => {
            if (res.confirm) {
              cancelOrder({orderId: item.orderId}).then(response => {
                if (response.isError) return
                that.$utils.showToast({ title: '取消成功' })
                item.orderStatus = -1
              })
            }
          }
        })
      } else {
        checkCancelPaidOrder({orderId: item.orderId}).then(response => {
          if (response.isError) return
          this.$pt.navigateTo({url: '/pages/personal/order/cancel-order/main?memberId=' + item.memberId + '&orderId=' + item.orderId})
        })
      }
    },
    getOrderDic() {
      getDict('UserOrderDTO.orderStatus').then((response) => {
        // console.log('订单状态字典')
        // console.log(response)
        if (response.isError) return
        this.orderStatusMap = response.data.orderStatus
      }).catch(() => {
      })
    },
    tabClick(e) {
      this.orders = []
      this.currentPage = 1
      this.activeIndex = e.mp.detail.index
      this.getOrderList()
    },
    // 确认收货
    receivingGoods(item) {
      const that = this
      this.$pt.showModal({
        content: '是否确认收货？',
        success(res) {
          if (res.confirm) {
            console.log('收货')
            that.doReceiveGoods(item)
          } else if (res.cancel) {
            console.log('用户取消')
          }
        }
      })
    },
    linkToDetail(sku) {
      let value = JSON.stringify(sku)
      this.$pt.navigateTo({url: `/pages/personal/order/refund-detail/main?sku=${value}`})
    },
    // 去订单详情
    queryOrderInfo(item) {
      this.$pt.navigateTo({ url: `/pages/personal/order/detail/main?orderId=${item.orderId}` })
    },
    // 查看物流
    queryExpress(item) {
      if (item.apartOrderIds.length > 1) {
        this.$pt.navigateTo({ url: `/pages/personal/order/express-view/main?orderId=${item.orderId}` })
      } else {
        this.$pt.navigateTo({ url: `/pages/personal/order/express-detail/main?orderId=${item.orderId}` })
      }
    },
    getOrderList() {
      const params = {
        customerMemberId: this.getCustomerId,
        orderStatusInfo: this.activeIndex || '',
        currentPage: this.currentPage,
        size: 10
      }
      this.nodata = false
      pageCustomerOrder(params).then(response => {
        if (response.isError) return
        if (response.data.total === 0) {
          this.nodata = true
          this.pullLoad.finished = true
          return
        }
        response.data.records.forEach(item => {
          item.goodsCount = 0
          const apartOrderSet = new Set()
          item.orderGoodsList.forEach(value => {
            item.goodsCount += value.goodsNum
            if (value.samplePartnerRatio && value.sampleAnchorRatio) {
              value.sampleLessRatio = ((value.samplePartnerRatio * 1) - (value.sampleAnchorRatio * 1)).toFixed(2)
              this.$set(item, 'sampleLessRatio', value.sampleLessRatio)
            }
            apartOrderSet.add(value.apartOrderId)
          })
          item.apartOrderIds = [...apartOrderSet]
          this.orders.push(item)
        })
        this.currentPage++
        if (this.orders.length === 0 || this.orders.length >= response.data.total) {
          this.pullLoad.finished = true
        }
      }).catch(() => {
      })
    },
    doReceiveGoods(item) {
      doReceiveGoods({orderId: item.orderId}).then(response => {
        if (response.isError) return
        this.$utils.showToast({ title: '确认收货成功' })
        this.orders = []
        this.currentPage = 1
        this.pullLoad.finished = false
        this.getOrderList()
      }).catch(() => {
      })
    }
  }
}
</script>

<style lang="less" scoped>
.ratio-bar{
  background: #f7f9fb;
  border-radius: 2px;
  .anchor-ratio-field{
    width: 63px;
    height: 20px;
    padding: 0 1px;
    box-sizing: border-box;
    border-radius: 3px;
    background: #e1e1e1;
    /deep/ .van-cell {
      margin: 0;
      border-top-left-radius: 3px;
      border-bottom-left-radius: 3px;
      border-top-right-radius: 0px;
      border-bottom-right-radius: 0px;
      padding: 0px 5px!important;
      height: 18px!important;
      min-height: 18px!important;
      line-height: 18px!important;
    }
    /deep/ .van-field__input{
      font-size: 11px!important;
      height: 18px!important;
      min-height: 18px!important;
      line-height: 18px!important;
    }
  }
  .per-tag{
    background: #e1e1e1;
    border-top-right-radius: 3px;
    border-bottom-right-radius: 3px;
  }
}
.item-bar-l{
  width: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  min-height: 86px;
}
.action-btn {
  color: #666;
  background-color: #fff;
  height: 24px!important;
  line-height: 24px!important;
  padding: 0px 15px!important;
  border: 1px solid #e9e9e9;
  border-radius: 50px;
}
.tabs-wrap{
  position: fixed;
  left: 0;
  width: 100%;
  /deep/ .van-tabs__scroll--line{
    background-color: #7427FF;
    height: 36px;
  }
  /deep/ .van-tab{
    color: white;
    line-height: 36px;
    background-color: unset;
  }
  /deep/ .van-tabs__nav {
    background-color: unset;
  }
  /deep/ .van-tab--active{
    font-weight: bold;
  }
  /deep/ .van-tabs__line{
    width: 15px !important;
    height: 2px !important;
    border-radius: 1.5px !important;
    background-color: white !important;
    left: 15px !important;
    bottom: 3px;
  }
}
.income {
  background: #ffe1d1;
  color: #ff5a00;
  font-size: 12px;
  border-radius: 5px;
  padding: 2px 4px;
  line-height: 1;
  display: inline-block;
}
.border-b {
  border-bottom: #e4e4e4 1px solid;
}
.order-div {
  background-color: #fff;
  border-radius: 5px;
  margin: 10px;
  font-size: 13px;
}
.line-h-1{
  line-height: 1;
}
.goods-prop {
  box-sizing: border-box;
  height: 22px;
  line-height: 22px;
  padding: 0 7px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  word-break: break-word;
  background-color: #F7F9FB;
  border-radius: 2px;
  max-width: 150px;
}
.goods-title {
  height: 20px;
  line-height: 20px;
  overflow:hidden;
  text-overflow:ellipsis;
  display:-webkit-box;
  -webkit-line-clamp:1;
  -webkit-box-orient:vertical;
  word-break:break-word;
  font-size: 16px;
  font-weight: bold;
  margin-right: 30px;
  margin-top: 3px;
}
.img-item {
  width: 90px;
  height: 90px;
  border-radius: 5px;
}
.order-btn {
  background-color: #fff;
  color: #666666;
  font-size: 13px;
  line-height: 1;
  display: inline-block;
  padding: 6px 12px;
  border-radius: 13.5px;
  border: #E9E9E9 1px solid !important;
  &.cancel-order{
    color: #7427ff;
    background-color: #fff;
    border: #7427ff 1px solid !important;
  }
}
.opration-row{
  text-align: right;
  border-top: 0.5px solid #E5E5E5;
  height: 50px;
  line-height: 50px;
}
.comfirm-btn{
  min-width: 52px;
  text-align: center;
  border: 1px solid #7427FF !important;
  color: #fff;
  background-color: #7427FF;
}
.mar-t-42{
  margin-top: 42px;
}
.nodata{
  padding-top: 100px;
}
</style>
